<?php
namespace tp5_lib\user\logic;

use tp5_lib\install\logic\Module;

class UserModule extends Module
{
    public function update()
    {
        $result=[
            "methods"=>[],
            "append"=>[],
            "login_call"=>[],
            "menu"=>[],
        ];
        $template=require __DIR__ . "/../" . config("module.config_dir") . "user.template.php";
        $this->scan("user",function($module,$config)use(&$result,$template){
            if(!empty($config["outside_login"])){
                foreach($config["outside_login"] as $id => $item){
                    $item = array_merge($template["outside_login"]["template"],$item);
                    $item["module"]=$module;
                    $result["methods"][$id] = $item;
                }
            }
            if(!empty($config["register_append"])){
                $result["append"][]=$config["register_append"];
            }
            if(!empty($config["login_call"])){
                $result["login_call"][]=$config["login_call"];
            }
            if(!empty($config["menu"])){
                $result["menu"]=array_merge($result["menu"],$config["menu"]);
            }
        });
        $config=[
            "list"=>[],
            "monopoly"=>[],
            "pc"=>[],
            "mobile"=>[],
            "app"=>[],
        ];
        foreach($result["methods"] as $id => $method){
            if($this->list[$method["module"]]["status"] !== "installed"){
                continue;
            }
            $config["list"][$id]=$method;
            if($method["monopoly"]){
                $config["monopoly"][] = [$id,$method["monopoly"],$method["priority"]];
            }
            if($method["pc"]) $config["pc"][] = $id;
            if($method["mobile"]) $config["mobile"][] = $id;
            if($method["app"]) $config["app"][] = $id;
        }
        usort($config["monopoly"],function($a,$b){
            return $a[2] < $b[2];
        });
        $config["register_append"]=$result["append"];
        $config["login_call"]=$result["login_call"];
        $config["menu"]=$result["menu"];
        $this->write("user",$config);
        return true;
    }
}
